<template>
  <div class="camera">
    <basic-container>
      <avue-crud :option="option"
                 :table-loading="loading"
                 :data="data"
                 :page.sync="page"
                 ref="crud"
                 @row-del="rowDel"
                 v-model="form"
                 :permission="permissionList"
                 @row-update="rowUpdate"
                 @row-save="rowSave"
                 :before-open="beforeOpen"
                 @search-change="searchChange"
                 @search-reset="searchReset"
                 @selection-change="selectionChange"
                 @current-change="currentChange"
                 @size-change="sizeChange"
                 @refresh-change="refreshChange"
                 @on-load="onLoad">
        <template slot="menuLeft" slot-scope="scope">
          <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permissionList" @click="handleDelete">删 除</el-button>
        </template>
        <template slot-scope="scope" slot="menu">
          <el-button type="text"
                     size="small"
                     icon="el-icon-video-camera"
                     plain
                     v-if="permission.camera_play"
                     class="none-border"
                     @click="handlePlayer(scope.row)">播放
          </el-button>
        </template>
        <!-- 地图表单自定义 -->
        <template slot="mapForm">
          <div v-if="showMap">
            <baidu-map class="map" :center="center" :zoom="zoom" @ready="handler">
              <el-input placeholder="关键词查询" v-model="searchWord" style="position:absolute;top:10px;left:10px;width:180px;">
                <template slot="append">
                  <el-button icon="el-icon-search" id="citySearch"></el-button>
                </template>
              </el-input>
              <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
              <bm-marker :position="mapPosition" :dragging="true"></bm-marker>
            </baidu-map>
          </div>
        </template>
      </avue-crud>
      <el-dialog
        title="视频播放"
        append-to-body
        :visible.sync="PlayerBox"
        @close="closePlay"
        width="555px">
        <LivePlayer :videoUrl="videoUrl" live muted stretch playback-rate></LivePlayer>
      </el-dialog>
    </basic-container>
  </div>
</template>

<script>
import {getList, remove, update, add, getcamera,getspldz} from "@/api/mmhi/camera";
import {mapGetters} from "vuex";
import LivePlayer from "@liveqing/liveplayer";
import {validateDigit} from "@/api/mmhi/validate";


export default {
  data() {
    return {
      videoUrl:'',
      dialogVisible: false,
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      attachBox: false,
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 30,
        dialogWidth: 950,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        viewBtn: true,
        playBth: true,
        selection: true,
        //excelBtn: true,
        dialogClickModal: false,
        column: [
          {
            label: "摄像头名称",
            prop: "sxtmc",
            align: "center",
            span: 30,
            search: true,
            rules: [{
              required: true,
              message: "请输入摄像头名称",
              trigger: "blur"
            }]
          },{
            label: "摄像头ID",
            align: "center",
            prop: "sxtid",
            rules: [{
              required: true,
              validator: validateDigit,
              trigger: "blur"
            }]
          },
          {
            label: "安装位置",
            align: "center",
            prop: "azwz",
            rules: [{
              required: true,
              message: "请输入安装位置",
              trigger: "blur"
            }]
          },
          {
            label: "所属区域",
            align: "center",
            prop: "ssqy",
            rules: [{
              required: true,
              message: "所属区域",
              trigger: "blur"
            }]
          },
          {
            label: "视频流地址",
            align: "center",
            prop: "spldz",
            rules: [{
              required: true,
              message: "视频流地址",
              trigger: "blur"
            }]
          },
          {
            label: '',
            prop: 'map',
            span: 24,
            hide: true,
            formslot: true,
          },
          {
            label: "经度",
            align: "center",
            width:90,
            prop: "jd",
            rules: [{
              required: true,
              message: "请输入经度",
              trigger: "blur"
            }]
          },
          {
            label: "纬度",
            prop: "wd",
            width:90,
            align: "center",
            rules: [{
              required: true,
              message: "请输入纬度",
              trigger: "blur"
            }]
          },
          {
            label: "是否在线",
            prop: "sfzx",
            type: "select",
            align: "center",
            dicData: [
              {
                label: "否",
                value: 0
              },
              {
                label: "是",
                value: 1
              },
            ],
            hide: false,
            rules: [{
              required: true,
              message: "请输入是否在线",
              trigger: "blur"
            }]
          },
        ]
      },
      data: [],
      mapPosition: {
        lng: 121.4472540000,
        lat: 31.3236200000
      },
      center: {
        lng: 121.4472540000,
        lat: 31.3236200000
      },
      zoom: 10,
      dragging: false,
      showMap: true,
      searchWord: "",
      PlayerBox: false,
    };
  },
  components: {
    LivePlayer
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.camera_add, true),
        viewBtn: this.vaildData(this.permission.camera_view, true),
        delBtn: false,
        editBtn: this.vaildData(this.permission.camera_edit, true),
        playBth: this.vaildData(this.permission.camera_play, true),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    player () {
      return this. $refs. videoPlayer. player
    },
  },
  methods: {
    closePlay(){
      this.PlayerBox=false;
      this.videoUrl=""
    },
    // 弹出视频
    handlePlayer(row) {
      debugger
      this.PlayerBox=true
      getspldz(row.id).then(response => {
        this.url =response.data.data;
        this.videoUrl= this.url
      });
    },
    rowSave(row, done, loading) {
      debugger
      add(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowUpdate(row, index, done, loading) {
      debugger
      update(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    handleDownload(row) {
      window.open(`${row.link}`);
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      debugger
      if (["edit", "view"].includes(type)) {
        getcamera(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      const {releaseTimeRange} = params;
      let values = {
        ...params,
      };
      if (releaseTimeRange) {
        values = {
          ...params,
          releaseTime_datege: releaseTimeRange[0],
          releaseTime_datelt: releaseTimeRange[1],
        };
        values.releaseTimeRange = null;

        this.query.releaseTimeRange = null;
      }
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(values, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    handler({BMap, map}) {
      let _this = this;
      map.addEventListener('click', function(e) {
        _this.form.jd = e.point.lng
        _this.form.wd = e.point.lat
      });

      _this.$nextTick(() => {
        document.getElementById('citySearch').addEventListener('click', function() {
          let localSearch = new BMap.LocalSearch(map)
          localSearch.setSearchCompleteCallback(searchResult => {
            let poi = searchResult.getPoi(0)
            if(!poi) {
              return _this.$message.warning('该地址不存在')
            } else {
              _this.center = {
                lng: poi.point.lng,
                lat: poi.point.lat
              }
              _this.form.jd = poi.point.lng
              _this.form.wd = poi.point.lat
            }
          });
          localSearch.search(_this.searchWord);
        });
      })
    },
  },
};
</script>

<style lang="scss">
.camera {
  .el-form-item__label {
    width: 100px !important;
  }
  .avue-form__row {
    .el-form-item__content {
      margin-left: 100px !important;
    }
  }
}
</style>
<style lang="scss" scoped>
.map {
  width: 100%;
  height: 500px;
}

</style>

